<template>
  <div class="upload-container">
    <el-form-item :label="labels">
      <el-alert
        title="第一张图片默认为商品封面图片，可拖动排序"
        type="warning"
      />
      <!-- <el-input v-model="prop" type="hidden" placeholder="图片路径" /> -->
      <div class="upload_buttom">
        <el-button :style="{background:color,borderColor:color}" icon="el-icon-picture" size="mini" type="primary" @click="addimglist">
          插入图库图片
        </el-button>
        <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
          上传本地图片
        </el-button>
      </div>
      <template>
        <UploadList
          list-type="picture-card"
          :files="imageUrl"
          :handle-preview="handlePictureCardPreview"
          @remove="Remove"
        />
      </template>
    </el-form-item>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :action="uploadfile(imgs)"
        :headers="headers()"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确定
      </el-button>
    </el-dialog>

    <!-- 查看大图 -->
    <el-dialog :visible.sync="dialogVisibleimgshow" append-to-body :title="'查看图片'">
      <div style="height:500px;overflow: auto;margin-bottom: 10px;text-align: center;">
        <el-image
          :src="dialogImageUrl"
          fit="cover"
        />
      </div>

    </el-dialog>

    <el-dialog :visible.sync="dialogFileVisible" append-to-body :title="'插入图库图片'">
      <div style="height:500px;overflow: auto;margin-bottom: 10px;">
        <el-checkbox-group
          v-model="checked"
          :max="5"
        >
          <div v-for="(fit,index) in imglists" :key="index" class="imglist">
            <template>
              <el-image
                style="width: 110px; height: 110px;float:left;margin-left: 5px;
    margin-right: 5px;
    margin-bottom: 10px;margin-top:10px;"
                :src="fit.url"
                fit="cover"
              />
              <el-checkbox
                class="chekckbox"
                :label="fit.url"
                @change="changecheck(fit,index)"
              >使用({{ changebytes(fit.bytes) }})</el-checkbox>
            </template>
          </div>
        </el-checkbox-group>
      </div>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      <div class="buttom_group">
        <el-button @click="dialogFileVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmitcheck">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getImagesList } from '@/api/publics'
import Pagination from '@/components/Pagination'
import { changebytes } from '@/utils/core'
import UploadList from './components/upload-list'

export default {
  name: 'MultiImg',
  components: { Pagination, UploadList },
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    prop: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 20
    },
    imgs: {
      type: Array,
      default() {
        return []
      }
    },
    labels: {
      type: String,
      default: '封面图片'
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogFileVisible: false,
      dialogVisibleimgshow: false,
      dialogImageUrl: '',
      bashurl: process.env.VUE_APP_BASE_API,
      listObj: {},
      fileList: [],
      checked: [],
      checkeditem: this.imgs,
      total: 0,
      imglists: [],
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+id'
      },
      imageUrl: []
    }
  },
  methods: {
    changebytes,
    async fetchData() {
      const res = await getImagesList(this.listQuery)
      this.listLoading = false
      this.imglists = res.data
      this.total = res.count
      if (this.imgs.length <= 0) this.checkeditem = []
    },
    addimglist() {
      this.checked = []
      this.dialogFileVisible = true
      this.fetchData()
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    changecheck(value, index) {
      if ((this.checkeditem.length || this.checked.length) >= this.limit) {
        this.$message('最多只能上传' + this.limit + '张图片')
        return false
      }
    },
    handleSubmitcheck() {
      if (this.checkeditem.length >= this.limit) {
        this.$message('最多只能上传' + this.limit + '张图片')
        return false
      }
      this.checked.some((item, i) => { this.checkeditem.push(item) })
      this.$emit('successCategory', this.checkeditem)
      this.imageUrl = this.imgs
      this.dialogFileVisible = false
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有图片上传成功。如果有网络问题，请刷新页面并重新上传!')
        return
      }
      if ((this.checkeditem.length + arr.length) > this.limit) {
        this.$message('最多只能上传' + this.limit + '张图片')
        return false
      }
      arr.some((item, i) => { this.checkeditem.push(item.url) })
      this.$emit('successCategory', this.checkeditem)
      this.imageUrl = this.imgs
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    headers() {
      return {
        'Authorization': `Bearer ${getToken()}`
      }
    },
    uploadfile(domain) {
      this.imageUrl = domain
      return this.bashurl + '/admin/images/upload'
    },
    handleSuccess(response, file) {
      if (response === '上传超时') {
        this.$message.error(response.file)
        return false
      }
      console.log(response)
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.file.url
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file
      this.dialogVisibleimgshow = true
    },
    Remove(file) {
      const fileList = this.imageUrl
      fileList.splice(fileList.indexOf(file), 1)
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      // console.log(888888)
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
.upload_buttom{
  display: block;
}
.imglist{
  float: left;
  width: 120px;
}
.buttom_group{
  display: block;
}
.chekckbox{
  display: inline-block;
    padding-left: 5px;
    line-height: 19px;
    font-size: 14px;
}
</style>
